
package com.bear.cmcc.NetTestHTTP.asynTask;

import com.bear.cmcc.NetTestHTTP.NationalInfoActivity;
import com.bear.cmcc.NetTestHTTP.NetworkTestApp;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class LoginVerifyTask extends AsyncTask<Object, Integer, Boolean> {
    private Activity activity;

    private boolean isLogined = false;

    private String encodedIMSI;

    private String strContent;

    private UserInfo userInfo;

    public LoginVerifyTask(Activity activity) {
        super();
        this.activity = activity;
        TelephonyManager tm = (TelephonyManager) activity
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = tm.getSubscriberId();
        encodedIMSI = Tools.encodeIMSI(imsi);// ���Ի�IMSI�ţ�D27932C49BFD43C7043AE347085F6C9C
        CommonValue.imsi = encodedIMSI;
        userInfo = new UserInfo();
    }

    @Override
    protected Boolean doInBackground(Object... arg0) {
        InputStream is = null;
        DataOutputStream dos = null;
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(CommonValue.BASE_URL);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setReadTimeout(15000);
            httpUrlConn.setConnectTimeout(20000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setInstanceFollowRedirects(true);
            httpUrlConn.setRequestProperty(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
            httpUrlConn.connect();

            StringBuilder builer = new StringBuilder();
            builer.append("methodName=").append(URLEncoder.encode("User.Verify", "gbk"))
                    .append("&imsi=").append(URLEncoder.encode(encodedIMSI, "gbk"));

            dos = new DataOutputStream(httpUrlConn.getOutputStream());
            dos.writeBytes(builer.toString());
            dos.flush();

            int rc = httpUrlConn.getResponseCode();
            System.out.println("rc=" + rc);
            if (rc == HttpURLConnection.HTTP_OK) {
                is = httpUrlConn.getInputStream();
                int iChar;
                StringBuilder sbContent = new StringBuilder();
                while ((iChar = is.read()) != -1) {
                    sbContent.append((char) iChar);
                }
                strContent = new String(sbContent.toString().getBytes("ISO-8859-1"), "gbk");
                System.out.println("strContent=" + strContent);

                publishProgress(CommonValue.REQUEST_SUCCESS);
                return true;

            } else {
                publishProgress(CommonValue.REQUEST_FAIL);
                return false;
            }

        } catch (MalformedURLException e) {
            publishProgress(CommonValue.REQUEST_FAIL);
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            publishProgress(CommonValue.TIMEOUT);
            e.printStackTrace();
            return false;
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                    dos = null;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        switch (values[0]) {
            case CommonValue.REQUEST_FAIL:
                Tools.showMessage(activity, "登录失败");
                break;
            case CommonValue.TIMEOUT:
                Tools.showMessage(activity, "登录超时");
                break;
            case CommonValue.NETWORK_DOWN:
                Tools.showMessage(activity, "网络异常");
                break;
            default:
                break;
        }
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            try {
                JSONObject json = new JSONObject(strContent);
                int sts = json.getInt("sts");
                switch (sts) {
                    case 0:// �ѵ�¼
                        isLogined = true;
                        parseResult(strContent);
                        break;
                    case 1:
                        isLogined = false;
                        break;
                    case 2:
                        isLogined = false;
                        break;
                    default:
                        break;
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        forwardPage(isLogined);
        super.onPostExecute(result);
    }

    private void parseResult(String result) {
        try {
            JSONObject json = new JSONObject(result);
            userInfo.setLoginname(json.getString("login_name"));
            userInfo.setSessionid(json.getString("sessionid"));
            userInfo.setName(json.getString("name"));
            CommonValue.sessionId = json.getString("sessionid");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void forwardPage(boolean isLogined) {
        Log.e("scj", "易运维登录结果：" + isLogined);
        if (isLogined) {
            NetworkTestApp.getApp().setHaveLogin(true);
        }
        Intent intent = new Intent(activity, NationalInfoActivity.class);
        intent.putExtra("isLogined", isLogined);
        if (isLogined) {
            Tools.showMessage(activity, "用户[" + userInfo.getName() + "]已经登录");
            intent.putExtra("loginName", userInfo.getLoginname());
            intent.putExtra("userName", userInfo.getName());
        }
        activity.startActivity(intent);
        activity.finish();
    }

}
